import re
from pathlib import Path
from typing import List, TypedDict
from utils import chinese_to_arabic

# 输出目录
OUTPUT_DIR = Path('data/output')
# 输出目录不存在则创建
OUTPUT_DIR.mkdir(exist_ok=True)

# 文本片段的分隔特征字符串
SEPARATOR = "\n\n#---#\n\n"

# 条款数据结构
class ArticleRow(TypedDict):
    chapter_id:  int         # 第一章对应为1，第二章对应为2，如对应章节标题不是第几章，则该值为-1
    chapter_no:  str         # "第一章", "第二章"
    chapter_title:  str      # "章节标题", 注意章节标题中间的空格可以去掉
    article_id: int          # 第一条对应为1，第二条对应为2，如果只是章节标题的文本，而不是条款的文本，则该值为-1
    article_no: str          # "第一条", "第二条", "第三条"
    text: str                # "条款的详细文本......


def format_regulations(text: str) -> tuple[str, List[ArticleRow]]:
    """
    格式化文本，将文本按照章节和条款进行划分，返回标题和条款列表。

    参数:
    text (str): 需要格式化的文本

    返回:
    tuple[str, List[ArticleRow]]: 标题和条款列表的元组
    """
    # 编译正则表达式匹配章节和条款
    chapter_pattern = re.compile(r'^第\s*([零一二三四五六七八九十百千]+)\s*章\s*(.*)$')
    article_pattern = re.compile(r'^第\s*([零一二三四五六七八九十百千]+)\s*条\s*(.*)$')

    result = []
    lines = text.split('\n')

    # 状态变量
    title: str = ""
    current_chapter_id = -1
    current_chapter_no = ""
    current_chapter_title = ""
    current_article_id = -1
    current_article_no = ""
    current_article_content = []
    in_article = False

    for line in lines:
        stripped = line.strip()
        if not stripped:  # 跳过空行
            continue

        # 检查是否是标题：
        if title == "":
            title = stripped
            continue

        # 检查是否是章节行
        chapter_match = chapter_pattern.match(stripped)
        if chapter_match:
            # 保存上一个条款（如果有）
            if in_article:
                result.append({
                    'chapter_id': current_chapter_id,
                    'chapter_no': current_chapter_no,
                    'chapter_title': current_chapter_title,
                    'article_id': current_article_id,
                    'article_no': current_article_no,
                    'text': '\n'.join(current_article_content)
                })
                in_article = False

            # 更新章节信息
            current_chapter_id = chinese_to_arabic(chapter_match.group(1))  # 章节ID递增
            current_chapter_no = f"第{chapter_match.group(1)}章"
            current_chapter_title = chapter_match.group(2).replace(" ", "")

            # 添加章节标题行
            result.append({
                'chapter_id': current_chapter_id,
                'chapter_no': current_chapter_no,
                'chapter_title': current_chapter_title,
                'article_id': -1,
                'article_no': "",
                'text': ""
            })
            continue

        # 检查是否是条款行
        article_match = article_pattern.match(stripped)
        if article_match:
            # 保存上一个条款（如果有）
            if in_article:
                result.append({
                    'chapter_id': current_chapter_id,
                    'chapter_no': current_chapter_no,
                    'chapter_title': current_chapter_title,
                    'article_id': current_article_id,
                    'article_no': current_article_no,
                    'text': '\n'.join(current_article_content)
                })

            # 开始新条款
            current_article_id = chinese_to_arabic(article_match.group(1))
            current_article_no = f"第{article_match.group(1)}条"
            current_article_content = [article_match.group(2)]
            in_article = True
            continue

        # 普通行：添加到当前条款内容
        if in_article:
            current_article_content.append(stripped)

    # 处理最后一个条款
    if in_article:
        result.append({
            'chapter_id': current_chapter_id,
            'chapter_no': current_chapter_no,
            'chapter_title': current_chapter_title,
            'article_id': current_article_id,
            'article_no': current_article_no,
            'text': ''.join(current_article_content)
        })

    return title, result


def main(path: str):
    src_path = Path(path)
    with open(src_path, "r", encoding="utf-8") as f:
        text = f.read()
        title, result = format_regulations(text)
    for row in result:
        print(row, "\n")

    # 获取原文件名
    filename = src_path.stem

    # 格式化结果数据
    result_str_list: list[str] = []
    for row in result:
        if row["article_id"] < 0:
            continue
        result_str_list.append(f"{title}\n{row['chapter_title']}\n{row['text']}")

    # 输出到文件
    output_path = OUTPUT_DIR.joinpath(filename+".txt")
    with open(output_path, "w", encoding="utf-8") as f:
        f.write(SEPARATOR.join(result_str_list))


if __name__ == "__main__":
    import fire
    fire.Fire(main)
